//
//  AppDelegate.swift
//  WeiBo09
//
//  Created by 裘明 on 15/8/31.
//  Copyright © 2015年 qm. All rights reserved.
//

import UIKit
import AFNetworking

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "SwitchRootViewController:", name: MQSwitchRootViewController, object: nil)
        
        // 设置导航条显示的颜色
        setupAppearance()
        
        // 设置网络
         setupNetwork()
        
        // 设置UITabBarController为Windows的根控制器
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defultRootViewController()
        window?.makeKeyAndVisible()
        
        return true
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self, name: MQSwitchRootViewController, object: nil)
    }
    
    /// 却换控制器
    ///
    /// - parameter notification: Controller
    func SwitchRootViewController(notification: NSNotification) {
        
        window?.rootViewController = (notification.object != nil) ? WelcomeViewController() : MainViewController()
    }
    
    
    /// 登录逻辑判断
    private func defultRootViewController() -> UIViewController {
        // 1.判断用户是否登录
        if UserAccountViewModel.sharedUserAccount.userLogin {
            
            // 2.判断是否是新版本
            return isNewVersion() ? NewFeatureViewController() : WelcomeViewController()
        }
        // 3.如果没有登录返回Main
        return MainViewController()
    }
    
    /// 判断是否是新版本
    private func isNewVersion() -> Bool {
//        printLog(NSBundle.mainBundle().infoDictionary)
        
        // 1.获取当前版本信息
        let bundelVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
        
        // 2.之前保存的版本号
        let versionKey = "com.qm.WeiBo09"
        let sendboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(versionKey)
        
        // 3.保存当前的版本号
        NSUserDefaults.standardUserDefaults().setDouble(bundelVersion, forKey: versionKey)
        
        // 4.比较版本，返回信息
        return bundelVersion > sendboxVersion
    }
    
    /// 设置导航条的显示颜色
    private func setupAppearance() {
        
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
    
        // 设置网络指示器
    private func setupNetwork() {
        AFNetworkActivityIndicatorManager.sharedManager().enabled = true
        
        // 设置缓存大小,内存缓存4M，磁盘缓存20M
        let cache = NSURLCache(memoryCapacity: 4 * 1024 * 1024, diskCapacity: 20 * 1024 * 1024, diskPath: nil)
        NSURLCache.setSharedURLCache(cache)
    }



}

